package com.example.nettywebsocketdemo.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author: ZhaoJie
 * @Date: 2022/3/28
 * @Description :
 * @Modify :
 * ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
public class MytextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame message) throws Exception {
        System.out.println("服务器收到消息 " + message.text());
        //回复消息
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + message.text()));
        //启动定时器，向前端发送消息
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("你好，这是后端的消息"));
            }
        }, 1000, 5000);
    }
}
